from django.shortcuts import render,redirect
from django.http import HttpResponse,JsonResponse
from django.core.urlresolvers import reverse



# Create your views here.
from .. import models
from . viewsIndex import uploads
# 数据分页需导入
from django.core.paginator import Paginator
# 导入Q对象
from django.db.models import Q
import re
import os
# 文件上传
from web.settings import BASE_DIR


# 商品添加
def goodsadd(request):
    # 获取所有的商品分类
    data = models.Cates.objects.extra(select = {'paths':'concat(path,id)'}).order_by('paths')
    # 分配数据
    context = {'cateslist':data}
    return render(request,'myadmin/goods/add.html',context)


# 执行商品添加
def goodsinsert(request):
    # 接受数据
    data = request.POST.dict()
    data.pop('csrfmiddlewaretoken')

    data['cateid'] = models.Cates.objects.get(id=data['cateid'])
    try:
        bool(float(data['price']))
    except:
        return HttpResponse('<script>alert("价格请输入数字");history.back(-1);</script>')
    # 处理上传的商品主图
    myfile = request.FILES.get('pic_url')
    if myfile:
        data['pic_url'] = uploads(myfile)
    else:
        return HttpResponse('<script>alert("必须上传商品主图");history.back(-1);</script>')

    # 执行数据的添加
    ob = models.Goods(**data)
    ob.save()
    return HttpResponse('<script>alert("添加成功");location.href="'+reverse('myadmin_goods_index')+'"</script>')



# 商品显示列表
def goodsindex(request):
    # 查询
    data = models.Goods.objects.filter().exclude(status = -1)




    # ------------------搜索---------------------
    # 
    # 获取搜索条件和数据
    types = request.GET.get('types')
    keywords = request.GET.get('keywords')

    # 判断是否有搜索条件
    if types:
        # 判断搜索的类型
        if types == "all":
            # Q 对象 <===> or   filter <====>  and
            data = data.filter(Q(title__contains = keywords)|Q(cateid__name__icontains = keywords))
        elif types == 'price':
            # 获取价格区间
           arr = keywords.split(',')
           # 相当于 and
           data = data.filter(price__gte = arr[0]).filter(price__lte = arr[1])
        elif types == 'cates':
            # print(cateid)
            data = data.filter(cateid__in = models.Cates.objects.filter(name__contains=keywords))

            # else:
            #     return HttpResponse('<script>alert("查询失败");location.href="'+reverse('myadmin_user_index')+'"</script>')
        elif types == 'status':
            arr = {'新品':0,'热卖':1,'下架':2}
            if keywords in arr:
                data=data.filter(status=arr[keywords])
            else:
                return HttpResponse('<script>alert("查询失败");location.href="'+reverse('myadmin_goods_index')+'"</script>')

        else:
            search = {types+'__contains':keywords}
            data = data.filter(**search)
    # ---------------------------------------
  


    # ----------------数据分页-----------------------
    # 
    # 实例化分页类  参数1,获取的所有的数据对象   参数2 每页显示多少条
    paginator = Paginator(data,4)

    # 获取当前页码数 ===> ?p=n
    p = request.GET.get('p',1)
    # 获取当前页的数据
    goodslist = paginator.page(p)
    # page_range  能得到页码数的区间
    print(paginator.page_range)
    # ---------------------------------------


    context = {'goodslist':goodslist}
    return render(request,'myadmin/goods/index.html',context)

# 删除后台会员 逻辑删除
def goodsdel(request,uid):
    try:
    # 根据uid获取用户对象,修改状态
        ob = models.Goods.objects.get(id = uid)
        ob.status = -1
        ob.save()
        return HttpResponse('<script>alert("删除成功");location.href="'+reverse('myadmin_goods_index')+'"</script>')
    except:
        return HttpResponse('<script>alert("删除失败");location.href="'+reverse('myadmin_goods_index')+'"</script>')


# 修改
def goodsedit(request,uid):
    # 根据uid显示编辑对象
    ob = models.Goods.objects.get(id = uid)
    # print(ob)
    # 判断请求方式
    if request.method == 'GET':
        # 获取所有的商品分类数据
        cateslist = models.Cates.objects.extra(select = {'paths':'concat(path,id)'}).order_by('paths')
        
        # 分配数据
        context = {'uinfo':ob,'cateslist':cateslist}
        # 显示编辑列表
        return render(request,'myadmin/goods/edit.html',context)
    elif request.method == 'POST':
        # 执行更新
        data = request.POST.dict()
        data.pop('csrfmiddlewaretoken')
        
        ob.cateid = models.Cates.objects.get(id = data['cateid'])
        ob.title = request.POST['title']
        # return HttpResponse('ok')
        ob.price = request.POST.get('price')
        ob.store = request.POST.get('store')
        ob.status = request.POST.get('status')
        ob.info = request.POST.get('info')
        # 判断是否更新了主图
        myfile = request.FILES.get('pic_url')
        if myfile:
            try:
                # 删除原来上传的头像
                os.remove(BASE_DIR+ob.pic_url)
            except:
                pass
            # 更新主图
            ob.pic_url = uploads(myfile)

        ob.save()

        return HttpResponse('<script>alert("修改成功");location.href="'+reverse('myadmin_goods_index')+'"</script>')

# def is_number(num):
#     pattern = re.compile(r'^[0-9]\d*\.\d*|[-+]?\.?[0-9]\d*$')
#     result = pattern.match(num)
#     if result:
#         return True
#     else:
#         return False
